//订单运费总览展示
(function ($) {
    var strOrder = '<div class="word-box wordBoxOut"><div class="whiteBar"></div><div class="word-box-con wordbox scrollBar" style="cursor: default;"></div><div class="triangle"></div></div>';
    $(document).off('click', '.estimatedCostDisplay');
    $(document).on('click', '.estimatedCostDisplay', function () {
        var _this = $(this),
            estBox = _this.closest('.estimatedCostDisplayBox'),
            pckid = _this.attr('pckid'),
            oheight = '',
            divTop = '',
            triangleTop = '';
        // 请求运费总揽数据
        $('#loading').modal('show');
        $.ajax({
            type: 'POST',
            url: 'package/getAgentAndLogisticFee.htm',
            data: {'packageId': pckid},
            dataType: 'html',
            success: function (data) {
                var estimatedCost = $(strOrder);
                var newStr = data;
                if (_this.find('.word-box').length < 1 && newStr != '') {
                    estimatedCost.find('.wordbox').append(newStr);
                    $(".wordBoxOut").remove();
                    estBox.append(estimatedCost);
                    divTop = estBox.find('.word-box').outerHeight();
                    oheight = '-' + (divTop + 12) + 'px';
                    triangleTop = (divTop - 2) + 'px';
                    estBox.find('.word-box').css({'top': oheight, 'display': 'block'});
                    estBox.find('.triangle').css({'top': triangleTop});
                }
                $('#loading').modal('hide');
            },
            error: function () {
                $('#loading').modal('hide');
            }
        });
    });

    //鼠标点击位置如果不是wordBoxOut，wordBoxOuthide;
    $(document).click(function (e) {
        if (!e) {
            var e = window.event;
        }
        //获取事件点击元素
        var targ = e.target;
        //获取元素名称
        var wordBoxOut = $(targ).closest('.estimatedCostDisplayBox').length;
        if (wordBoxOut != 1) {
            $('.estimatedCostDisplayBox').find('.wordBoxOut').remove();
        }
    });
})(jQuery);
//订单备注
(function ($) {
    var strOrder='<div class="word-box"><div class="whiteBar"></div><div class="word-in wordbox scroll-bar word-break1"></div><div class="triangle"></div></div>',
        hoverStoFn = '';
    $(document).on('mouseover','.hoverPrompt',function () {
        var yanModalObj = $(strOrder),
            placement = $(this).attr('data-placement'),
            newStr = $(this).attr('data-content');

        if(newStr) newStr = removeScriptContent(newStr);
        if ($(this).find('.word-box').length < 1) {
            yanModalObj.find('.wordbox').append(newStr);
            $(this).append(yanModalObj);
            var divTop = $(this).find('.word-box').outerHeight();
            $(this).find('.word-box').css({'top': '-' + (divTop+15) + 'px'});
            $(this).find('.triangle').css({'top': (divTop-2) + 'px'});
        }else if($(this).find('.word-box').length && !$(this).find('.word-box').find('.wordbox').text()){
            $(this).find('.word-box').find('.wordbox').append(newStr);
            var divTop = $(this).find('.word-box').outerHeight();
            $(this).find('.word-box').css({'top': '-' + (divTop+15) + 'px'});
            $(this).find('.triangle').css({'top': (divTop-2) + 'px'});
        }
        $('.tooltipHover').tooltip();
        $('.word-box').removeClass('show'); //把所有气泡移除掉show
        $(this).find('.word-box').addClass('show'); //给当前悬停的气泡加一个show
        clearTimeout(hoverStoFn); //清除延时器
    });
    //离开延迟隐藏，离开之后0.2秒在隐藏气泡，防止用户无法悬停到气泡上操作
    $(document).on('mouseout','.hoverPrompt',function () {
        var $that = $(this);

        hoverStoFn = setTimeout(function () { //离开气泡时，0.5秒之后在把show去掉
            $that.find('.word-box').removeClass('show');
        }, 200);
    });
})(jQuery);
//物流筛选
var logisticsStrategy = (function ($,W,D){
    var agentlist = '',//筛选栏
        agentIdAndDetilMap = '';//物流列表

    /*多选按钮的事件绑定*/
    $(D).off('click','.multipleChoice').on('click','.multipleChoice',function () {

        //是否需要初始化
        if($('.titlist').find('.logisticsScreen').length <= 1){
            logisticsStrategy.logisticsMessage();
        }

        // 国家多选时不能点击选择
        var countryState = $('td[cid="countryscreen"]').find('div.screen-modal-b').css('display');
        if (countryState === 'block') {
            $.fn.message({type:'error',msg:'请先确认好国家区域'});
            return false
        }
        $('.logisticsSearch').addClass('hide');
        $('#allLogistics').css('display','none');
        $('.multipleChoiceModal').css('display','block');
        $(this).css({'border-color':'#428bca','color':'#428bca'});

        // 清除多余显示Ipt
        var threeIpt =  $('.selList').find('input[type="checkbox"]');
        threeIpt.each(function(w,q){
            if ($(q).is(':checked') === false) {
                $(q).closest('label').remove();
            }
        });
        // 默认选中第一个
        $('.logisticsScreen[cid="-1"]').click();
    });
    /*物流弹层分组点击事件绑定*/
    $(D).off('click','.logisticsScreen').on('click','.logisticsScreen',function () {
        logisticsScreen(this);
    });
    var logisticsScreen = function(obj){
        var id = $(obj).attr('cid'),// 当前cid
            $contentList = $('.contentList'),// 目标节点(第二框)
            $selList = $('.selList:visible'),
            state = $("#keepState").data("state"), //隐藏框的值
            allEle = '<label class="id"><input class="m-left10" type="checkbox" name="Logisticsselect" value="all"><span class="providerName">全部</span></label>',// 目标节点(第二框)第一值
            logisticsScreenList = (id == '-1') ? agentIdAndDetilMap['all'] : agentIdAndDetilMap[id], // 当前值匹配的物流
            ele = '';

        $contentList.children().remove();
        $contentList.append(allEle);
        $.each(logisticsScreenList,function (i,j) {
            var agentProviderName = j.agentProviderName,// 物流文本sure
                Id = j.id,// 物流标识值
                agentId = j.agentId,// 物流标识值
                isChecked = $selList.find('input[value="'+ Id +'"]:checked').length; // 匹配的已选中物流(第三框)

            if (state === 'allocated_has' || state === 'allocated_out' || state === 'approved' || state === 'processed') {
                var orderCount = j.orderCount ? j.orderCount : 0;// 只有上面集中状态有订单数量
                ele += '<label class='+agentId+'><input class="m-left10" type="checkbox" name="Logisticsselect"' +
                    ' value="'+Id+'" ' + (isChecked ? 'checked' : '') + '>' +
                    '<span class="providerName" data-id='+Id+'>'+agentProviderName+'</span><span class="count">（'+ orderCount +'）</span></label>';// 生成节点
            } else {
                ele += '<label class='+agentId+'><input class="m-left10" type="checkbox" name="Logisticsselect"' +
                    ' value="'+Id+'" ' + (isChecked ? 'checked' : '') + '>' +
                    '<span class="providerName" data-id='+Id+'>'+agentProviderName+'</span></label>';// 生成节点
            }
        });
        $contentList.append(ele);

        // 全选框选中状态
        var boxTwoCheckLen = 0,// 第二框选中计数器
            $boxTwoFirstIpt = $contentList.find('input[type="checkbox"][value="all"]'),//  第二框的全选框
            $boxTwoAllIpt = $contentList.find('input[type="checkbox"]:not([value="all"])');// 第二框所有节点
        // 第二框选中循环计数
        $boxTwoAllIpt.each(function(q,w){
            if ($(w).is(':checked')) {
                boxTwoCheckLen += 1;
            }
        })
        $boxTwoFirstIpt.prop('checked',$boxTwoAllIpt.length === boxTwoCheckLen);// 全选框选中状态
    }

    /*--------------------------物流筛选模板 -   START--------------------------*/

    //多选box注册事件
    $(D).off('click','.content input[name="Logisticsselect"]');
    $(D).on('click','.content input[name="Logisticsselect"]',function(){
        var listOut = $('.multipleChoiceModal').find('.content');
        var selListOut = $('.multipleChoiceModal').find('.selList');
        if ($(this).is(':checked')) {
            boxCheckedHandle($(this),listOut,selListOut,1);// 当前节点/当前节点父级/目标节点集合/选中状态
        } else {
            boxCheckedHandle($(this),listOut,selListOut,0);
        }
    });
    //多选 sellist box 注册事件 目标节点取消选中
    $(D).off('click','.selList input[type="checkbox"]');
    $(D).on('click','.selList input[type="checkbox"]',function(){
        var thisVal = $(this).val(),
            $facingAllBtn = $('.multipleChoiceModal .content').find('input[type="checkbox"][value="all"]'),// 当前全选框
            ckeckLen = 0,
            $facingAllIpt = $('.multipleChoiceModal .content').find('input[type="checkbox"]:not([value="all"])');// 当前全选框以外的input

        if (!$(this).is(':checked')) {
            $('.multipleChoiceModal').find('.content input[type="checkbox"][value="'+thisVal+'"]').prop('checked',false);
            $(this).closest('label').remove();
            buildBoxList();//生成selList
        }
        // 更改当前全选状态
        // 当前全选框以外的input选中计数
        $facingAllIpt.each(function (w,q) {
            if ($(q).is(':checked')) {
                ckeckLen += 1;
            }
        })
        $facingAllBtn.prop('checked', ckeckLen === $facingAllIpt.length);// 更改当前全选状态
    });
    //多选里 box选中、取消选中处理
    var boxCheckedHandle = function(obj,listOut,selListOut,type){// 当前节点/当前节点父级/目标节点集合/选中状态
        var boxVal = $(obj).val(),// 当前节点值
            $facingAllBtn = listOut.find('input[type="checkbox"][value="all"]'),// 当前全选框
            ckeckLen = 0;
            $facingAllIpt = listOut.find('input[type="checkbox"]:not([value="all"])');// 当前全选框以外的input
        if (boxVal == 'all') {
            var allCodeObj = $(listOut).find('input[type="checkbox"]');
            if (type == 0) {
                var $facingAllIpt = listOut.find('input[type="checkbox"]:not([value="all"])');// 当前全选框以外的input
                allCodeObj.prop('checked',false);// 全选框状态
                $facingAllIpt.each(function (i,j) {
                    var handleVal = $(j).closest('label').prop('class');//预处理值
                    selListOut.find('label[class="'+ handleVal +'"]').remove();//当前全选框的选项在第三框清除
                })
            } else {
                allCodeObj.prop('checked',true);
            }
        }else{
            var codeObj = $(selListOut).find('input[type="checkbox"][value="'+boxVal+'"]');// 与当前节点值匹配的目标节点
            if (type == 0) {
                codeObj.prop('checked',false);
                codeObj.closest('label').remove();
            } else {
                codeObj.prop('checked',true);
            }
            // 更改当前全选状态
            // 当前全选框以外的input选中计数
            $facingAllIpt.each(function (w,q) {
                if ($(q).is(':checked')) {
                    ckeckLen += 1;
                }
            })
            $facingAllBtn.prop('checked', ckeckLen === $facingAllIpt.length);// 更改当前全选状态
        }
        buildBoxList();//生成selList
    };
    //生成selList
    var buildBoxList = function(){
        var $multipleChoiceModal = $('.multipleChoiceModal'),// 当前modal层
            allBoxObj = $multipleChoiceModal.find('.content input[type="checkbox"]:checked'),// 当前选中input
            listOutObj = $multipleChoiceModal.find('.selList');// 目标节点容器
        allBoxObj.each(function(){
            if ($(this).val() !=  'all') {
                var thisVal = $(this).val(),
                    textHtmlFacing = $(this).closest('label')[0].outerHTML,
                    $moretext = $(textHtmlFacing).find('span.count')[0],
                    moreText = !$moretext ? '' : $moretext.outerHTML,
                    textHtml = textHtmlFacing.replace(moreText,'');
                    $match = listOutObj.find('input[value="'+thisVal+'"]').closest('label');// 当前节点是否在目标容器有一份
                // 重复添加拦截
                if ($match.length === 0) {
                    listOutObj.append(textHtml);
                    listOutObj.find('input[value="'+thisVal+'"]').prop('checked',true);
                }
            }
        })
    };

    /*--------------------------物流筛选模板 -   END--------------------------*/

    //弹层取消事件
    $(D).off('click','input[cid="abolish"]').on('click','input[cid="abolish"]',function () {
        var childrenLen = $('.logisticsSearch').find('span').length;
        if (childrenLen > 0) {
            $(this).closest('.multipleChoiceModal').css('display','none');
            $('.logisticsSearch').removeClass('hide');
        } else {
            $('#allLogistics').css('display','block');
            $(this).closest('.multipleChoiceModal').css('display','none');
            $('.multipleChoice').css({'border-color':'#ccc','color':'#333'});
        }
    });
    //弹层确定事件
    $(D).off('click','input[cid="sure"]');
    $(D).on('click','input[cid="sure"]',function(){
        var $pitchName = $('#authIdDiv .selList').find('.providerName'),//第三框选中文本节点
            $spanEle = $('.logisticsSearch').find('.spanEle');// 目标文本节点
        // 选中数量大于零确定事件
        if($pitchName.length > 0) {
            $(this).closest('.multipleChoiceModal').css('display','none');// 当前modal隐藏
            $('.eliminate').siblings().remove();
            $.each($pitchName,function (i,j) {
                var pitchName = $(j).text(),
                    spanEle = '<span class="m-left0 m-right10 spanEle">'+pitchName+'</span>',
                    flag = true;
                $('.eliminate').before(spanEle);
            });
            $('.logisticsSearch').removeClass('hide');
            var $providerName = $('.selList').find('.providerName'),
                id = '';
            $.each($providerName,function (i,j) {
                id += ($(j).attr('data-id')+ ',')
            });
            var val = id.substring(0, id.length -1),
                key = 'authid';
            setCondition(key,val);
        } else {
            $.fn.message({type:'error',msg:'请至少选中一个物流渠道！'});
        }
    });

    // 清除已选定多物流
    $(document).off('click', '.eliminate').on('click', '.eliminate', function () {
        $('.logisticsSearch').addClass('hide');
        $('#allLogistics').css('display','block');
        $('.multipleChoiceModal input').prop('checked',false);// 恢复选中状态
        $('.logisticsSearch').find('span').remove();
        $('.multipleChoice').css({'border-color':'#ccc','color':'#333'});
        $('#authIdAll').click();
    });

    return{
        //页面初始化加载物流信息
        logisticsMessage: function () {
            var titChoice = '';
            $.each(agentlist,function (i,j) {
                titChoice += '<a class="classify-a m-top5 pointer logisticsScreen" cid="' + j.id + '">' + j.agentName + '</a>';
            });
            $('.titlist').append(titChoice);
            $('.logisticsScreen[cid="-1"]').click();
        },
        setLogisticsData: function(data){
            if(data.agentIdAndDetilMap){
                agentIdAndDetilMap = JSON.parse(data.agentIdAndDetilMap);
            }
            if(data.agentlist){
                agentlist = JSON.parse(data.agentlist);
            }
        }
    }
})(jQuery,window,document);

/*--------------------------待打单有货 - 按SKU分组板块  START--------------------------*/

/*常规板块 - 分组板块切换*/
$(document).on('click', '.groupSwitchClick', function () {
    $('#loading').modal('show');
    var objDivType = $(this).attr('data-type');
    if (objDivType == 'normal') {
        // 常规板块跳转
        myjStorage.set("allocated_has_moduleName", "normal")();   //记录cookies
        var go = $(this).attr("data-go");
        $("#" + go).click();
    } else if (objDivType == 'group') {
        // 分组板块跳转
        myjStorage.set("allocated_has_moduleName", "group")();   //记录cookies
        $.ajax({
            type: "POST",
            url: "package/orderGroup/index.htm",
            data: {},
            dataType: "html",
            success: function (data) {
                $('#rightBody').html(data);
                $('#loading').modal('hide');
                $("#rightBody").css("display", "");
                /*加载导航*/
                groupCommSearchList();
                /*加载数据*/
                groupOrderList(100);
            },
            error: function () {
                $('#loading').modal('hide');
            }
        });
    }
});

/*导航列表加载*/
var groupCommSearchList = function () {
    var url = "package/orderGroup/commSearchList.htm";
    $.ajax({
        type: "POST",
        url: url,
        data: {},
        dataType: "html",
        success: function (data) {
            $('#commSearchDiv').html(data);
        },
        error: function () {
            $('#loading').modal('hide');
        }
    });
};

/*Ajax包裹分组分页列表加载*/
var groupOrderList = function (pageNum) {
    var $groupKeepState = $("#groupKeepState");
    // 物流商id
    var agentId = $groupKeepState.data("agentid");
    if (agentId == undefined || agentId == '') {
        agentId = "-1";
    }
    // 物流方式id
    var authId = $groupKeepState.data("authid");
    if (authId == undefined) {
        authId = "";
    }
    // 升降序
    var ascOrDesc = $groupKeepState.data("ascordesc");
    if (ascOrDesc == undefined || ascOrDesc == '') {
        ascOrDesc = "0";
    }
    // 排序字段
    var orderField = $groupKeepState.data("orderfiled");
    // 面单打印状态
    var printMd = $groupKeepState.data("printmd");
    if (printMd == undefined) {
        printMd = "0";
    }
    // 包裹类型
    var productStatus = $groupKeepState.data("productstatus");
    // 仓库id
    var storageId = $groupKeepState.data("storageid");
    if (storageId == undefined || storageId == "") {
        storageId = "0";
    }
    // 是否拣货备注
    var jhComment = $groupKeepState.data("jhcomment");
    if (jhComment == undefined || jhComment == '') {
        jhComment = "1";
    }
    // 是否多品混包
    var skusItems = $groupKeepState.data("skusitems");
    if (skusItems == undefined || skusItems == '') {
        skusItems = "1";
    }
    //为了控制每页显示的条数，增加pageSize
    if (pageNum == undefined) {
        pageNum = $('#pageSize').val();
    }
    var url = "package/orderGroup/list.htm?pageNo=1&pageSize=" + pageNum + "&agentId=" + agentId + "&authId=" + authId + "&ascOrDesc="
        + ascOrDesc + "&orderField=" + orderField + "&printMd=" + printMd + "&productStatus=" + productStatus + "&storageId=" + storageId
        + "&jhComment=" + jhComment + "&skusItems=" + skusItems,
    $shopGroupId = $('#shopGroupId'),
    shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';
    if (shopGroupId) url += '&shopGroupId=' + shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件

    $('#loading').modal('show');
    $.ajax({
        type: "GET",
        url: url,
        data: {},
        dataType: "html",
        success: function (data) {
            $('#dxmBody').html(data);
            // 刷新统计数值(已打面单、未打面单)
            refreshGroupCountNum();
            $('#loading').modal('hide');
        },
        error: function () {
            $('#loading').modal('hide');
        }
    });
    // 订单左侧状态流程统计数值
    refreshStateCount();
};

/*统计数值刷新*/
var refreshGroupCountNum = function () {
    var $groupKeepState = $("#groupKeepState");
    var storageId = $groupKeepState.data("storageid");
    var agentId = $groupKeepState.data("agentid");
    var authId = $groupKeepState.data("authid");
    var productStatus = $groupKeepState.data('productstatus'),
        ajaxPostData = {
            storageId: storageId,
            agentId: agentId,
            authId: authId,
            productStatus: productStatus
        },
        $shopGroupId = $('#shopGroupId'),
        shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

    if (shopGroupId) ajaxPostData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件

    $.ajax({
        type: "POST",
        url: 'package/orderGroup/getGroupCount.json',
        data: ajaxPostData,
        dataType: "json",
        success: function (data) {
            var unPrintMdNum = data.unPrintMdNum;
            var printedMdNum = data.printedMdNum;

            if(($("#productStatus3").is(":checked") || $("#jhCommentInput").is(":checked")) && !$("#productStatus1").is(":checked") && !$("#productStatus2").is(":checked")) {
                unPrintMdNum = 0;
                printedMdNum = 0;
            }

            $("#unPrintMdNum").html(unPrintMdNum);     //未打面单组数
            $("#printedMdNum").html(printedMdNum);     //已打面单组数
        },
        error: function () {
        }
    });
};

/*设置查询条件*/
var groupSetCondition = function (key, val, obj) {
    $("#groupKeepState").data(key, val);
    groupSetClass(obj);

    if ("agentid" == key) {
        // 根据选择的物流商控制物流方式checkbox的对应显示
        var agentId = val;
        var $authCkBoxes = $("#groupAuthIdDiv").find("[name='auths']");
        $authCkBoxes.each(function () {
            $(this).prop('checked', false);
            if (agentId != -1) {
                if ($(this).data("agentid") == agentId) {
                    $(this).parent("label").show();
                } else {
                    $(this).parent("label").hide();
                }
                $("#authMore").hide();
            } else {    //全部物流商
                $(this).parent("label").show();
                $("#authMore").show();
                $('.showOtherAuth').hide();
                $("#authMore").attr('data-value', 0).find('.text-more').html('更多');
            }
        });
        $("#groupAuthIdAll").click();    // 选定任意一个物流商后都要重置物流方式为全部
    }

    // 订单搜索
    groupOrderList();
};

/*设置当前选中效果*/
var groupSetClass = function (obj) {
    $(obj).parent().find(".myj-active").removeClass("myj-active");
    $(obj).addClass("myj-active");
};

/*设置包裹类型*/
var groupSetProductStatus = function (obj) {
    var $groupKeepState = $("#groupKeepState");
    var productStatus = getCheckBoxValByName("productStatus");
    $groupKeepState.data("productstatus", productStatus);
    checkExtraItem();

    removeActive(obj);
    if ($("#productStatusAll").is(".myj-active")) {
        $groupKeepState.data("skusitems", "1");
        $groupKeepState.data("jhcomment", "1");
        $groupKeepState.data("productstatus", "1,2");
    }
    groupOrderList();
};

/*设置物流方式*/
var groupSetAuth = function (obj) {
    var $groupKeepState = $("#groupKeepState");
    var auths = getCheckBoxValByName("auths");
    $groupKeepState.data("authid", auths);

    removeActive(obj);
    if ($("#groupAuthIdAll").is(".myj-active")) {
        $groupKeepState.data("authid", "");
    }
    groupOrderList();
};

/*物流方式全部*/
$(document).on('click', '#groupAuthIdAll', function () {
    var $groupKeepState = $("#groupKeepState");
    $groupKeepState.data("authid", "");
    $("input[name='auths']").prop("checked", false);
    $("#groupAuthIdAll").addClass("myj-active");
    groupOrderList();
});

/*检查拣货备注、多品混包checkbox*/
var checkExtraItem = function () {
    var skSelect = $("#productStatus3").is(":checked");
    var jhSelect = $("#jhCommentInput").is(":checked");
    if (skSelect) {
        $("#groupKeepState").data("skusitems", "1");
    } else {
        $("#groupKeepState").data("skusitems", "-1");
    }
    if (jhSelect) {
        $("#groupKeepState").data("jhcomment", "1");
    } else {
        $("#groupKeepState").data("jhcomment", "-1");
    }
};

/*checkbox选择与全部切换*/
var removeActive = function (obj) {
    var div = $(obj).closest('div');
    var length = div.find('input[type=checkbox]:checked').length;
    if (length > 0) {
        div.find('a.myj-aFocus').removeClass('myj-active');
    } else {
        div.find('a.myj-aFocus').addClass('myj-active');
    }
};

/*包裹状态全部*/
$(document).on('click', '#productStatusAll', function () {
    var $groupKeepState = $("#groupKeepState");
    $groupKeepState.data("skusitems", "1");
    $groupKeepState.data("jhcomment", "1");
    $groupKeepState.data("productstatus", "1,2");
    $("input[name='productStatus']").prop("checked", false);
    $("input[name='skusitems']").prop("checked", false);
    $("input[name='jhcomment']").prop("checked", false);
    $("#productStatusAll").addClass("myj-active");
    groupOrderList();
});

/*设置排序方式*/
var groupSetOrderFiled = function (key, val, obj) {
    var $groupKeepState = $("#groupKeepState");

    var orderField = $groupKeepState.data("orderfiled");
    $groupKeepState.data(key, val);
    groupSetClass(obj);

    var spanObj = $(obj).find("span");
    var attrClass = $(spanObj).attr("class");
    $("#groupOrderFieldDiv").find("span").removeClass("myjCaretDown").removeClass("myjCaretUp");
    $(spanObj).addClass(attrClass);

    var isTop = $(spanObj).hasClass("myjCaretUp");
    var isDown = $(spanObj).hasClass("myjCaretDown");

    if (val == orderField) {
        if (isTop) {
            $(spanObj).removeClass("myjCaretUp").addClass("myjCaretDown");
            $groupKeepState.data("ascordesc", 1);
        } else if (isDown) {
            $(spanObj).removeClass("myjCaretDown").addClass("myjCaretUp");
            $groupKeepState.data("ascordesc", 0);
        }
    } else {
        // 首次点击按包裹数和按SKU数排序时,采取倒序排
        if (val == "groupPackageNum" || val == "groupSkuNum") {
            $(spanObj).removeClass("myjCaretDown").addClass("myjCaretDown");
            $groupKeepState.data("ascordesc", 1);
        } else {
            $(spanObj).removeClass("myjCaretDown").addClass("myjCaretUp");
            $groupKeepState.data("ascordesc", 0);
        }
    }
    groupOrderList();
};

/*获取当前checkbox所选Group*/
var getParaDataForGroupBatchOperate = function (normalGroupItemSku) {
    var $groupKeepState = $("#groupKeepState");
    // 物流商id
    var agentId = $groupKeepState.data("agentid");
    if (agentId == undefined || agentId == '') {
        agentId = "-1";
    }
    // 物流方式id
    var authId = $groupKeepState.data("authid");
    // 仓库id
    var storageId = $groupKeepState.data("storageid");
    if (storageId == undefined || storageId == "") {
        storageId = "0";
    }
    // 面单打印状态
    var printMd = $groupKeepState.data("printmd");
    if (printMd == undefined) {
        printMd = "0";
    }
    // 包裹类型
    var productStatus = $groupKeepState.data("productstatus");
    if(normalGroupItemSku == undefined){
        normalGroupItemSku = "";
    }
    return {
        "groupActionFlag": 1,
        "storageId": storageId,
        "agentId": agentId,
        "authId": authId,
        "printMd": printMd,
        "productStatus": productStatus,
        "normalGroupItemSku" : normalGroupItemSku
    };
};

/*批量标记分组面单拣货单打印状态*/
var groupBatchSignPackage = function (val, isPrint, type) {
    var normalGroupItemSku = getCheckBoxValByName("normalGroupItemSku");
    var extralGroupItem = getCheckBoxValByName("extralGroupItem");
    if (normalGroupItemSku == "" && extralGroupItem == "") {
        $.fn.message({type: "error", msg: "请至少选择一个分组"});
        return;
    }
    if (type == undefined) {        // type: 1 面单 2 拣货单
        if (val == 0) {
            type = 1;
        } else if (val == 1) {
            type = 2;
        }
    }
    if (val != -1 && val != 2) {
        var $signedBtn = $("#signedBtn");
        $signedBtn.attr("onclick", "groupBatchSetPrint('" + normalGroupItemSku + "','" + extralGroupItem + "'," + type + "," + isPrint + ");");
        if (type == 1 && isPrint == 1) {        // 面单 标记打印
            $("#signedModal").modal("show");
            $("#signSpan").html("面单");
            $("#signStateSpan").html("「已打印」");
            $signedBtn.html("标记为已打印");
        } else if (type == 2 && isPrint == 1) { // 拣货单 标记打印
            $("#signedModal").modal("show");
            $("#signSpan").html("拣货单");
            $("#signStateSpan").html("「已打印」");
            $signedBtn.html("标记为已打印");
        } else if (type == 1 && isPrint == 0) { // 面单 标记未打印
            $("#signedModal").modal("show");
            $("#signSpan").html("面单");
            $("#signStateSpan").html("「未打印」");
            $signedBtn.html("标记为未打印");
        } else if (type == 2 && isPrint == 0) {  // 拣货单 标记未打印
            $("#signedModal").modal("show");
            $("#signSpan").html("拣货单");
            $("#signStateSpan").html("「未打印」");
            $signedBtn.html("标记为未打印");
        }
    }
};

/*置为已打印*/
var groupBatchSetPrint = function (normalGroupItemSku, extralGroupItem, type, isPrint) {
    $("#signedModal").modal("hide");
    $("#printedModal").modal("hide");
    if (isNaN(isPrint)) {
        isPrint = 1;                // 默认设置为已打印
    }
    var url = 'package/batchSetPrint.json?extralGroupItem=' + extralGroupItem + '&type=' + type + '&isPrint=' + isPrint,
        $shopGroupId = $('#shopGroupId'),
        shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

    if (shopGroupId) url += '&shopGroupId=' + shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
    $('#loading').modal('show');
    $.ajax({
        type: "POST",
        url: url,
        data: getParaDataForGroupBatchOperate(normalGroupItemSku),
        dataType: "json",
        success: function (data) {
            var print = "已打印";
            if (isPrint == 0) {
                print = "未打印";
            }
            var successList = data.bor.successList;
            var failList = data.bor.failList;
            batchReturnProcess(successList, failList, "符合条件的订单已标记为" + print);
            groupOrderList();
        },
        error: function () {
            $.fn.message({type:'error',msg:'网络异常，请稍后重试！'});
            $('#loading').modal('hide');
        }
    });
};

/*批量发货*/
var isGroupBatchShip = false;
var groupBatchShipGoods = function (normal, extral) {
    var normalGroupItemSku,extralGroupItem;

    if(normal == undefined && extral == undefined) {            // 组批量
        normalGroupItemSku = getCheckBoxValByName("normalGroupItemSku");
        extralGroupItem = getCheckBoxValByName("extralGroupItem");
        if (normalGroupItemSku == "" && extralGroupItem == "") {
            $.fn.message({type: "error", msg: "请至少选择一个分组"});
            return;
        }
    }else {                                                     // 组单个
        if(normal != ""){
            normalGroupItemSku = normal;
            extralGroupItem = "";
        }
        if(extral != ""){
            extralGroupItem = extral;
            normalGroupItemSku = "";
        }
    }
    myjAlert.confirm({
        'content':'确定要发货？',
        'callback':function(v){
            if(v){
                if(isGroupBatchShip){
                    return;
                }
                isGroupBatchShip = true;
                var url = 'package/batchShipGoods.json?extralGroupItem=' + extralGroupItem,
                    $shopGroupId = $('#shopGroupId'),
                    shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

                if (shopGroupId) url += '&shopGroupId=' + shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
                $('#loading').modal('show');
                $.ajax({
                    type: "POST",
                    url: url,
                    data: getParaDataForGroupBatchOperate(normalGroupItemSku),
                    dataType: "json",
                    success: function(data){
                        if(data.code == 0){
                            var successList = data.bor.successList;
                            var failList 	= data.bor.failList;
                            batchReturnProcess(successList, failList, "订单已移入到「已交运」页！");
                            groupOrderList();
                        }else{
                            var msg = strFilterUrl(data.msg);
                            $.fn.message({type: "error", msg: msg});
                        }
                        isGroupBatchShip = false;
                    },
                    error:function(){
                        $('#loading').modal('hide');
                        isGroupBatchShip = false;
                    }
                });
            }
        }
    });
};

/*批量提交至平台（虚拟发货）*/
var isGroupBatchCommitPlatform = false;
var groupBatchCommitPlatform = function (normal, extral) {
    var normalGroupItemSku,extralGroupItem;
    if(normal == undefined && extral == undefined) {            // 组批量
        normalGroupItemSku = getCheckBoxValByName("normalGroupItemSku");
        extralGroupItem = getCheckBoxValByName("extralGroupItem");
        if (normalGroupItemSku == "" && extralGroupItem == "") {
            $.fn.message({type: "error", msg: "请至少选择一个分组"});
            return;
        }
    }else {                                                     // 组单个
        if(normal != ""){
            normalGroupItemSku = normal;
            extralGroupItem = "";
        }
        if(extral != ""){
            extralGroupItem = extral;
            normalGroupItemSku = "";
        }
    }
    myjAlert.confirm({
        'content':'确定要虚拟发货（提交至平台）？',
        'callback':function(v){
            if(v){
                if(isGroupBatchCommitPlatform){
                    return;
                }
                isGroupBatchCommitPlatform = true;
                var ajaxData = getParaDataForGroupBatchOperate(normalGroupItemSku),
                    $shopGroupId = $('#shopGroupId'),
                    shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

                if (shopGroupId) ajaxData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
                $('#loading').modal('show');
                $.ajax({
                    type: "POST",
                    url: "package/batchCommitPlatform.json?extralGroupItem=" + extralGroupItem,
                    data: ajaxData,
                    dataType: "json",
                    success: function(data){
                        if(data.code == 0){
                            var successList = data.bor.successList;
                            var failList 	= data.bor.failList;
                            batchReturnProcess(successList, failList, "物流跟踪号已提交到平台！");
                        }else{
                            var msg = strFilterUrl(data.msg);
                            $.fn.message({type: "error", msg: msg});
                            groupOrderList();
                        }
                        isGroupBatchCommitPlatform = false;
                    },
                    error:function(){
                        $('#loading').modal('hide');
                        isGroupBatchCommitPlatform = false;
                    }
                });
            }
        }
    });
};

/*（移入缺货）批量释放库存*/
var isGroupBatchFreeStock = false;
var groupBatchFreeStock = function () {
    var normalGroupItemSku = getCheckBoxValByName("normalGroupItemSku");
    var extralGroupItem = getCheckBoxValByName("extralGroupItem");
    if (normalGroupItemSku == "" && extralGroupItem == "") {
        $.fn.message({type: "error", msg: "请至少选择一个分组"});
        return;
    }
    if (isGroupBatchFreeStock) {
        return;
    }
    isGroupBatchFreeStock = true;
    var ajaxData = getParaDataForGroupBatchOperate(normalGroupItemSku),
        $shopGroupId = $('#shopGroupId'),
        shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

    if (shopGroupId) ajaxData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
    $('#loading').modal('show');
    $.ajax({
        type: "POST",
        url: "package/batchFreeStock.json?extralGroupItem=" + extralGroupItem,
        data: ajaxData,
        dataType: "json",
        success: function (data) {
            var successList = data.bor.successList;
            var failList = data.bor.failList;
            batchReturnProcess(successList, failList, "订单已移入到「待打单缺货」页！");
            groupOrderList();
            isGroupBatchFreeStock = false;
        },
        error: function () {
            $('#loading').modal('hide');
            isGroupBatchFreeStock = false;
        }
    });
};

/*批量打回待处理提示弹层*/
var showGroupBatchInvalid = function () {
    var normalGroupItemSku = getCheckBoxValByName("normalGroupItemSku");
    var extralGroupItem = getCheckBoxValByName("extralGroupItem");
    if (normalGroupItemSku == "" && extralGroupItem == "") {
        $.fn.message({type: "error", msg: "请至少选择一个分组"});
        return;
    }
    var $batchInvalidPackageModal = $("#batchInvalidPackageModal");
    $batchInvalidPackageModal.find(".btn-determine").attr("onclick", "groupBatchInvalidPackage()");
    $batchInvalidPackageModal.modal("show");
};

/*批量打回待处理*/
var groupBatchInvalidPackage = function () {
    var normalGroupItemSku = getCheckBoxValByName("normalGroupItemSku");
    var extralGroupItem = getCheckBoxValByName("extralGroupItem"),
        url = 'package/batchInvalid.json?extralGroupItem=' + extralGroupItem,
        $shopGroupId = $('#shopGroupId'),
        shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

    if (shopGroupId) url += '&shopGroupId=' + shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
    $('#loading').modal('show');
    $.ajax({
        type: "POST",
        url: url,
        data: getParaDataForGroupBatchOperate(normalGroupItemSku),
        dataType: "json",
        success: function (data) {
            $("#batchInvalidPackageModal").modal("hide");
            var successList = data.bor.successList;
            var failList = data.bor.failList;
            batchReturnProcess(successList, failList, "订单已移入到「待处理」页！");
            groupOrderList();
            $('#loading').modal('hide');
        },
        error: function () {
            $('#loading').modal('hide');
        }
    });
};

/*批量设置搁置提示弹层*/
var groupBatchSetVoidedConfirm = function () {
    var normalGroupItemSku = getCheckBoxValByName("normalGroupItemSku");
    var extralGroupItem = getCheckBoxValByName("extralGroupItem");
    if (normalGroupItemSku == "" && extralGroupItem == "") {
        $.fn.message({type: "error", msg: "请至少选择一个分组"});
        return;
    }
    var $batchGezhi = $("#batchGezhi");
    $batchGezhi.find(".btn-determine").attr("onclick", "groupBatchSetVoided()");
    $batchGezhi.modal("show");
};

/*批量设置搁置*/
var groupBatchSetVoided = function () {
    var normalGroupItemSku = getCheckBoxValByName("normalGroupItemSku");
    var extralGroupItem = getCheckBoxValByName("extralGroupItem");
    if (normalGroupItemSku == "" && extralGroupItem == "") {
        $.fn.message({type: "error", msg: "请至少选择一个分组"});
        return;
    }
    $("#batchGezhi").modal("hide");
    $('#loading').modal('show');
    var ajaxData = getParaDataForGroupBatchOperate(normalGroupItemSku),
        $shopGroupId = $('#shopGroupId'),
        shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

    if (shopGroupId) ajaxData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
    $.ajax({
        type: "POST",
        url: "package/batchSetVoided.json?extralGroupItem=" + extralGroupItem,
        data: ajaxData,
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
                var successList = data.bor.successList;
                var failList = data.bor.failList;
                batchReturnProcess(successList, failList, "订单已移入到「已搁置」页！");
                groupOrderList();
            } else {
                $.fn.message({type: "error", msg: data.msg});
            }
        },
        error: function () {
            $('#loading').modal('hide');
        }
    });
};

/*分组打印面单确认提示弹层*/
var groupPrintMd = function (normal, extral, singleOperate) {
    var normalGroupItemSku, extralGroupItem;
    if (normal == undefined && extral == undefined) {            // 组批量
        normalGroupItemSku = getCheckBoxValByName("normalGroupItemSku");
        extralGroupItem = getCheckBoxValByName("extralGroupItem");
        if (normalGroupItemSku == "" && extralGroupItem == "") {
            $.fn.message({type: "error", msg: "请至少选择一个分组"});
            return;
        }
    } else {                                                     // 组单个
        if (normal != "") {
            normalGroupItemSku = normal;
        }
        if (extral != "") {
            extralGroupItem = extral;
        }
    }
    $("#normalGroupItemSkuPrintSign").val(normalGroupItemSku);
    $("#extralGroupItemPrintSign").val(extralGroupItem);
    $("#singleOperate").val(singleOperate);
    // 分组打印面单只支持高速自动打印
    $("#pdfPrintDiv").hide();
    var puid = $("#puidForPrint").val();
    $('#printSingleConfirm').find(".btn-determine").attr("onclick", "groupBatchPrintExpressList(" + puid + ")");
    $("#gsAutoPrintRadio").prop('checked', true);
    $("#gsAutoPrintRadio").click();
    $('#tipPrintNums').hide(); // 将提示的有多少包裹号隐藏
    $('#printSingleConfirm').modal('show');
};

/*执行分组批量打印面单*/
var groupBatchPrintExpressList = function(puid){
    var printer = $("#allPrinterSelect").val();
    if(printer == '' || printer == undefined){
        checkDxmPlug({val: 1});
        return;
    }
    getGroupPrintAllData(puid);
};

/*获取分组全部打印数据*/
var getGroupPrintAllData = function(puid){
    var agentId = $("#groupKeepState").data("agentid");
    var normalGroupItemSku = $("#normalGroupItemSkuPrintSign").val();
    var extralGroupItem = $("#extralGroupItemPrintSign").val();

    if($("#singleOperate").val() != 1) {
        if (agentId == '' || agentId <= 0) {
            $.fn.message({type: "error", msg: "由于选择分组打印，请从页面上方的「物流商」中先选定一个物流商再「批量打印」！"});
            return;
        }
        /*var authId = $("#groupKeepState").data("authid");
        if (authId == '' || authId <= 0) {
            $.fn.message({type: "error", msg: "请选择一个或多个物流方式！"});
            return;
        }*/
    }

    var ajaxData = getParaDataForGroupBatchOperate(normalGroupItemSku),
        $shopGroupId = $('#shopGroupId'),
        shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

    if (shopGroupId) ajaxData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
    $.ajax({
        type: "POST",
        url: "package/getGroupPrintAllList.htm?extralGroupItem=" + extralGroupItem,
        data: ajaxData,
        dataType: "html",
        success: function (data) {
            $("#allPrinterDataDiv").html(data);
            $("#printSingleState").customModal("show");
            // 执行打印数据(共用)
            groupPrintAllData(puid);
        },
        error: function () {
            $('#loading').modal('hide');
        }
    });
};

/*执行打印全部订单数据*/
var groupPrintAllData = function(puid){
    var authId = $("#groupKeepState").data("authid");
    /*
     * 处理多渠道打印逻辑URL
     * 菜鸟打印&非菜鸟打印分开，遍历依次请求
     */
    $("#allPrintAllListTBody").find("tr").each(function(){
        var packageId = $(this).attr("data-id");
        var authId = $(this).attr("data-authid");
        var isCainiaoPrint = $(this).attr("data-isCainiaoPrint");

        var packageIdArr = [];
        packageIdArr[0] = packageId;

        // 准备依次请求打印的URL
        if(isCainiaoPrint == 1){
            // 菜鸟打印
            var printer = $("#printerSelect").val();
            $("#dxmPrintState").attr("data-cainiao",2);

            var perNum    = 100;
            var packLen   = packageIdArr.length;
            var n = Math.ceil(packLen / perNum);
            for (var i = 0; i < n; i++){
                var end = (i == n - 1) ? packLen : (i + 1) * perNum;
                var arr = packageIdArr.slice(i * perNum, end);
                executeCainiaoPrint(0, printer, arr.join(","), "", authId, "", "");
            }
        }else {
            // 非菜鸟打印
            var isCos = $("#isCos").val();
            if(isCos == '' || isCos == undefined){
                isCos = 0;
            }
            var url = gitWinLocHref() + "printMbAuto.htm?puid=" + puid + "&dxmPrint=1&authId=" + authId+"&isCos="+isCos;
            batchAllDoPrint(url, packageIdArr);
        }
    });
};

/*打印拣货单*/
var groupPrintJh = function () {
    var normalGroupItemSku = getCheckBoxValByName("normalGroupItemSku");
    var extralGroupItem = getCheckBoxValByName("extralGroupItem");
    if (normalGroupItemSku == "" && extralGroupItem == "") {
        $.fn.message({type: "error", msg: "请至少选择一个分组"});
        return;
    }
    // 表单POST提交请求
    var data = getParaDataForGroupBatchOperate();
    var groupActionFlag = data['groupActionFlag'];
    var storageId = data['storageId'];
    var agentId = data['agentId'];
    var authId = data['authId'];
    var printMd = data['printMd'];
    var productStatus = data['productStatus'];

    var $groupPrintJhForm = $("#groupPrintJhForm");
    $groupPrintJhForm.find("input[name='normalGroupItemSku']").val(normalGroupItemSku);
    $groupPrintJhForm.find("input[name='extralGroupItem']").val(extralGroupItem);
    $groupPrintJhForm.find("input[name='groupActionFlag']").val(groupActionFlag);
    $groupPrintJhForm.find("input[name='storageId']").val(storageId);
    $groupPrintJhForm.find("input[name='agentId']").val(agentId);
    $groupPrintJhForm.find("input[name='authId']").val(authId);
    $groupPrintJhForm.find("input[name='printMd']").val(printMd);
    $groupPrintJhForm.find("input[name='productStatus']").val(productStatus);

    $groupPrintJhForm.attr("action", "groupPrintJh.htm");
    $groupPrintJhForm.submit();

    groupBatchSetPrint(normalGroupItemSku, extralGroupItem, 2, 1);      //标记为已打印拣货单
    
};

/*导出分组 - 显示导出勾选项和导出所有页*/
var groupShowExcelSelectAndAll = function (isAll) {
    $("#exportPayTime").hide();
    if (isAll == 0) {
        var normalGroupItemSku = getCheckBoxValByName("normalGroupItemSku");
        var extralGroupItem = getCheckBoxValByName("extralGroupItem");
        if (normalGroupItemSku == "" && extralGroupItem == "") {
            $.fn.message({type: "error", msg: "请至少选择一个分组"});
            return;
        }
        $("#exportOrderBtn").attr("onclick", "groupExportSelectPackage();");
    } else {
        $("#exportOrderBtn").attr("onclick", "groupExportAllPackage();");
    }
    $("#exportState").hide();
    $("#exportSelectAll").hide();
    $("#exportSelectAll").find("input").prop("checked", true);
    $("#exportTable").hide();
    $("#exportTable").find('table.excl td').html("");

    getTemplate("order");
    $('#exportModel input[name="isMaster"]').prop('checked',false);
    $('#exportModel input[cid="isMaster"]').prop('checked',true);
    $("#exportModel").modal("show");
};

/*导出分组 - 导出勾选项包裹中的订单*/
var groupExportSelectPackage = function () {
    var normalGroupItemSku = getCheckBoxValByName("normalGroupItemSku");
    var extralGroupItem = getCheckBoxValByName("extralGroupItem");
    if (normalGroupItemSku == "" && extralGroupItem == "") {
        $.fn.message({type: "error", msg: "请至少选择一个分组"});
        return;
    }
    var arr = "";
    var templateId = $("#exportTemplateSelect").val();
    var isMaster = $('#exportModel input[name="isMaster"]:checked ').val();
    if(+templateId === -1 || +templateId === -2) {
        arr = exportDataGetNew('exportModel'); //标准模板
    }else if (+templateId > 0) {
        arr = dataGetNew('exportModel'); //自定义模板
    }else {
        $.fn.message({type: "error", msg: "请选择模板类型!"});
        return;
    }
    var exportKeys = formatFieldFromArrayToString(arr);
    if (exportKeys == '') {
        $.fn.message({type: "error", msg: "您没有选择导出任何选项，请选择后再操作!"});
        return;
    }
    // isMaster 0 订单维度 1 包裹维度 2 产品维度
    var url = "order/exportPackageOrder.json?packageIds=" + "&exportKeys=" + exportKeys + "&exportStyle=" + isMaster + "&history=" + "&templateId=" + templateId
        + "&normalGroupItemSku=" + normalGroupItemSku + "&extralGroupItem=" + extralGroupItem,
        $shopGroupId = $('#shopGroupId'),
        shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

    if (shopGroupId) url += '&shopGroupId=' + shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
    groupBatchExportOrder(exportKeys, templateId, url);
};

/*导出分组 - 导出所有包裹订单*/
var groupExportAllPackage = function () {
    var isMaster= $('#exportModel input[name="isMaster"]:checked ').val();
    var arr = "";
    var templateId = $("#exportTemplateSelect").val();
    if(+templateId === -1 || +templateId === -2) {
        // 标准模板
        arr = exportDataGetNew('exportModel');
    } else if (templateId > 0) {
        arr = dataGetNew('exportModel');
        // 标准模板
    } else {
        $.fn.message({type: "error", msg: "请选择模板类型!"});
        return;
    }
    var exportKeys = formatFieldFromArrayToString(arr);
    if (exportKeys == '') {
        $.fn.message({type: "error", msg: "您没有选择导出任何选项，请选择后再操作!"});
        return;
    }
    exportKeys = encodeURIComponent(exportKeys);

    var eg = "";
    var ng = "";
    if ($("#productStatusAll").is(".myj-active")) {
        eg = "hasPickComment,skus_items";
        ng = "ALL";
    } else {
        var jhComment = $("#groupKeepState").data("jhcomment");
        var skusItems = $("#groupKeepState").data("skusitems");
        var productStatus = $("#groupKeepState").data("productstatus");
        if (jhComment == 1) {
            eg += "hasPickComment";
        }
        if (skusItems == 1) {
            eg += ",skus_items";
        }
        if(productStatus == ""){
            ng = "";
        }else {
            ng = "ALL";
        }
    }
    // isMaster 0 订单维度 1 包裹维度 2 产品维度
    var url = "order/exportPackageOrder.json?packageIds=" + "&exportKeys=" + exportKeys + "&exportStyle=" + isMaster + "&history=" + "&templateId=" + templateId
        + "&normalGroupItemSku=" + ng + "&extralGroupItem=" + eg,
        $shopGroupId = $('#shopGroupId'),
        shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

    if (shopGroupId) url += '&shopGroupId=' + shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
    groupBatchExportOrder(exportKeys, templateId, url);
};

/*导出分组 - 批量导出订单*/
var groupBatchExportOrder = function(exportKeys,templateId,url){
    var orderField = "auth_id";  //排序字段
    var isSearch = "1";          //升序or降序
    url += "&orderField=" + orderField + "&isSearch=" + isSearch;
    $("#exportPackageKeys").val(exportKeys);
    $("#exportTemplateId").val(templateId);
    $("#batchExportOrderModal").modal("show");
    $("#batchCheckReplicaProgressBar").css("display", "none");
    setTimeout(function () {
        $("#batchCheckReplicaProgressBar").css("width", 0 + "%");
        $("#batchCheckReplicaProgressBar").css("display", "");
    }, 10);
    $("#batchCheckReplicaProcessNum").html("0");
    $("#reportShow").empty();
    $('div[uid="downloadFill"]').removeClass('btn-dropdown').find('button[uid="dropdown"]').removeClass('btn-determine').addClass('btn-gray').prop('disabled', true).css('color', '#000000');
    $("#reportShow").css("color", "");
    var p = 0;		// 记录进度条的值
    $.ajax({
        type: "POST",
        url: url,
        data: getParaDataForGroupBatchOperate(),
        dataType: "json",
        success: function (data) {
            var uuid = data.uuid;
            checkProcessStatus(uuid, function (data) {
                var num = Math.round(data.num / data.totalNum * 100);
                if (num < p && data.code != 1) {
                    // 为了去掉变为n->0时的动画效果，在此先隐藏，然后再置0，最后再定时显示出来
                    $("#batchCheckReplicaProgressBar").css("display", "none");
                    setTimeout(function () {
                        $("#batchCheckReplicaProgressBar").css("display", "");
                    }, 1000);
                }
                p = num;
                if (data.code == 0 && (data.msg == '' || data.msg == 'loading')) {
                    $("#batchCheckReplicaProgressBar").css("width", num + "%");
                    $("#batchCheckReplicaProcessNum").text(data.num);
                    $("#reportShow").text("订单导出数据准备中，请稍等");
                } else if (data.code == 0 && data.msg == 'run') {
                    $("#batchCheckReplicaProgressBar").css("width", num + "%");
                    $("#batchCheckReplicaProcessNum").text(data.num);
                    $("#reportShow").text("订单正在导出中，请稍后下载...");
                } else if (data.code == -1) {
                    $("#batchCheckReplicaProgressBar").css("width", "100%");
                    $("#batchCheckReplicaProcessNum").text(data.num);
                    $("#reportShow").text(data.msg).css("color", "red");
                } else {
                    $("#batchCheckReplicaProgressBar").css("width", "100%");
                    $("#batchCheckReplicaProgressBar").removeClass("active");
                    $("#batchCheckReplicaProcessNum").text(data.totalNum);
                    $("#reportShow").empty();
                    $("#reportShow").html('导出文件已生成，文件将会在30分钟后失效,请立即下载<br/>');
                    $('div[uid="downloadFill"]').addClass('btn-dropdown').find('button[uid="dropdown"]').removeClass('btn-gray').addClass('btn-determine').prop('disabled', false).css('color', '#FFFFFF');
                    $('.highSpeedDownload').find('a').attr('href', data.msg);
                    var msg = data.msg;
                    var msgOver = getDownloadUrl(msg);
                    $('.standbDownload').find('a').attr('href', msgOver);
                }
            });
        },
        error: function (msg) {
        }
    });
};

/*--------------------------待打单有货 - 按SKU分组板块  END--------------------------*/

/** 待处理刷新物流规则 **/
var isRefreshLogisticRule = false;
var refreshLogisticRule = function () {
    if(isRefreshLogisticRule){
        return;
    }
    isRefreshLogisticRule = true;
    var shopId = $("#keepState").data("shopid");
    var platform = $("#keepState").data("platform");
    var allRefresh = $('#approvedOrderRefreshRule input:radio[name=refreshApprovedLogis]:checked').val();

    var p = 0;		// 记录进度条的值
    $("#refreshOrderRuleModal").modal("show");
    $("#refreshOrderRuleProgressBar").css("width", "0");
    $("#refreshOrderRuleModal_status").html("刷新中...");
    $("#refreshOrderRuleModal_processDetail").html("");
    $.ajax({
        type: "POST",
        url: 'order/refreshLogisticRule.json',
        data: {
            "shopId": shopId,
            "platform": platform,
            "allRefresh" : allRefresh
        },
        dataType: "json",
        success: function (data) {
            var uuid = data.uuid;
            checkProcessStatus(uuid, function(data){
                var num = (parseInt(data.num) / parseInt(data.totalNum)).toFixed(2) * 100;
                var status = "刷新中...";
                if(num < p && data.code != 1){
                    // 为了去掉变为n->0时的动画效果，在此先隐藏，然后再置0，最后再定时显示出来
                    $("#refreshOrderRuleProgressBar").css("display", "none");
                    setTimeout(function(){
                        $("#refreshOrderRuleProgressBar").css("display", "");
                    },1000);
                }
                p = num;
                if(data.code==0){
                    $("#refreshOrderRuleProgressBar").css("width", num + "%");
                }else{
                    status = "已完成!";
                    $("#refreshOrderRuleProgressBar").css("width", "100%");
                    $("#refreshOrderRuleProgressBar").removeClass("active");
                }
                $("#refreshOrderRuleModal_status").html(status);
                $("#refreshOrderRuleModal_processDetail").html(data.msg);
            });
            isRefreshLogisticRule = false;
        },
        error: function () {
            $('#loading').modal('hide');
            isRefreshLogisticRule = false;
        }
    });
};

var openRefreshRuleDia = function () {
    var $paidOrderRefreshRule = $('#paidOrderRefreshRule');
    $paidOrderRefreshRule.find('input[name=refreshPaidLogis][value = "0"]').prop("checked", true);
    $paidOrderRefreshRule.modal('show');
};

var openRefreshLogisRuleDia = function () {
    var $approvedOrderRefreshRule = $('#approvedOrderRefreshRule');
    $approvedOrderRefreshRule.find('input[name=refreshApprovedLogis][value = "1"]').prop("checked", true);
    $approvedOrderRefreshRule.modal('show');
};

var showModOrverSeaShipModel = function () {
    $('#modOrverSeaShipModel').modal('show');
};

var showBatchSetCustomCommentModal = function () {
    var ids = getCheckBoxValByName("packageId");
    if (ids == "") {
        $.fn.message({type: "error", msg: "请至少选择一个订单"});
        return;
    }
    $('#batchSetCustomCommentDiv span.module').each(function () {
        $(this).data('type',0);
        $(this).children().remove();
    });
    $('#batchSetCustomCommentModal').modal('show');
};

var batchSetCustomComment = function (initCustom,obj) {
    var packageIds = getCheckBoxValByName("packageId"),
        history = $('#keepState').data('history');

    if (packageIds === '') {
        $.fn.message({type: "error", msg: "请至少选择一个订单"});
        return;
    }
    var isGreen = '', isYellow = '', isOrange = '', isRed = '', isViolet = '', isBlue = '', cornflowerBlue = '',
        pink = '', teal = '', turquoise= '';

    if (+initCustom === 0 || +initCustom === 2) {
        var $signCont = '';
        if(+initCustom === 0){
            $signCont = $('#batchSetCustomCommentDiv').find('span.batchSetCustomModul');
        }else if( +initCustom === 2){
            $signCont = $(obj).closest('.dropBatchSetCusBox').find('a.signCont');
        }
        $.each($signCont,function (i,j) {
            var uid = $(j).attr('uid'),
                dataType = $(j).data('type');

            if(uid === 'moduleA') isGreen = dataType;
            if(uid === 'moduleB') isYellow = dataType;
            if(uid === 'moduleC') isOrange = dataType;
            if(uid === "moduleD") isRed = dataType;
            if(uid === "moduleE") isViolet = dataType;
            if(uid === "moduleF") isBlue = dataType;
            if(uid === "moduleW") cornflowerBlue = dataType;
            if(uid === "moduleX") pink = dataType;
            if(uid === "moduleY") teal = dataType;
            if(uid === "moduleZ") turquoise = dataType;
        });
        if(+isGreen === 0 && +isYellow === 0 && +isOrange === 0 && +isRed === 0 && +isViolet === 0 && +isBlue === 0
            && +cornflowerBlue === 0 && +pink === 0 && +teal === 0 && +turquoise === 0){
            $.fn.message({type: "error", msg: "请选择要设置的标记！"});
            return;
        }
    }
    $('#loading').modal('show');
    $.ajax({
        type: "POST",
        url: 'order/batchSetCustomComment.json',
        data: {
             packageIds:packageIds,
             isGreen: isGreen,
             isYellow: isYellow,
             isOrange: isOrange,
             isRed: isRed,
             isViolet: isViolet,
             isBlue: isBlue,
             cornflowerBlue: cornflowerBlue,
             pink: pink,
             teal: teal,
             turquoise:turquoise,
             history: history ? 'history' : ''//区分历史订单和120天内订单
        },
        dataType: "json",
        success: function (data) {
            $('#loading').modal('hide');
            if (data.code == 0) {
                $.fn.message({type: "success", msg: "操作成功!"});
                refreshAjaxPage();
            }else {
                $.fn.message({type: "error", msg: data.msg});
            }
        },
        error: function () {
            $('#loading').modal('hide');
        }
    });
};

var batchInitCustomComment = function () {
    var ids = getCheckBoxValByName("packageId");
    if (ids === '') {
        $.fn.message({type: "error", msg: "请至少选择一个订单"});
        return;
    }
    myjAlert.confirm({
        'content': '您确定要清除已有标记？',
        'callback': function(v) {
            if (v) {
                batchSetCustomComment(1);
            }
        }
    });
};

/*** 合联物流start ***/
var heLianChange = function(){
    var authId	= $("#batchProviderSelect").val();
    // helian物流方式
    var packageIds = getCheckBoxValByName("packageId");
    if(packageIds == ''){
        $.fn.message({type:"error",msg:"请至少选择一个订单"});
        return;
    }
    $("#batchUpdateProviderBtn0").css("display","none");
    $("#batchUpdateProviderBtn1").css("display","none");
    $('#loading').modal('show');
    $.ajax({
        type: "POST",
        url: 'order/showBatchHeLian.htm',
        data: {"packageIds":packageIds,"authId":authId},
        dataType: "html",
        success: function(data){
            $("#batchUpdateProvider").modal("hide");
            $("#heLianShip").html(data);
            $('#loading').modal('hide');
            $("#heLianShip").modal("hide");
            $("#heLianShip").modal("show");
        },
        error:function(){
            $('#loading').modal('hide');
        }
    });
};

/** 批量修改合联 **/
var batchUpdateHeLian= function(){
    $('#loading').modal('show');
    $.ajax({
        type: "POST",
        url: 'order/batchUpdateHeLian.json',
        data: $("#heLianForm").serialize(),
        dataType: "json",
        success: function(data){
            $('#loading').modal('hide');
            if(data.code == 0){
                batchReturnProcess(data.bor.successList, data.bor.failList, "报关信息完整的订单已移入到「运单号申请」页！");
                $("#heLianShip").modal("hide");
                refreshAjaxPage();
            } else {
                $.fn.message({type:"error",msg:data.msg});
                $("#heLianShip").modal("hide");
                $("#heLianShip").modal("show");
            }
        },
        error:function(){
            $('#loading').modal('hide');
        }
    });
};
/** 批量修改合联  end**/


/** 从运费总览 更新包裹物流方式 **/
var updatePackageLogistic = function (obj, packageId, authId, agentNameType, agentProviderName, type, apacPickUpType, showCodAmount, orderPlatform, codType, sizeType, agentPackageCountType) {      //type:  0列表页，  1订单详情页
    if(!packageId || !authId){
        $.fn.message({type: 'error', msg: '包裹号或者物流方式为空'});
        return;
    }
    if(+$(obj).data('value') === 1){
        $.fn.message({type: 'error', msg: '已选择此物流方式'});
        return;
    }
    myjAlert.confirm({
        content: '物流方式确定要更换为：' + agentProviderName + '？',
        callback: function (v) {
            if (v) {
                var agentNameTypeArr = [22, 105, 256, 419, 353, 458, 655,448,734];
                if(agentNameTypeArr.indexOf(+agentNameType) !== -1) {
                    //速卖通线上发货、PostPony、中乌速递、合联物流方式 需要在包裹详情页设置物流
                    if (+type === 1) {
                        //详情页
                        var platform = $('#detailPlatform').val();
                        $('#agentAndLogisticFeeModal').modal('hide');
                        showLogisticInfo(authId, agentNameType, platform, apacPickUpType, showCodAmount, codType, sizeType, agentPackageCountType);
                    } else if (!+type) {
                        //列表页需要跳到详情页
                        var url = 'package/detail.htm';
                        $('#dxmPackageDetailDiv').empty();
                        $('#loading').modal('show');
                        $.ajax({
                            type: 'POST',
                            url: url,
                            data: {packageId: packageId},
                            dataType: 'html',
                            success: function (data) {
                                $('#loading').modal('hide');
                                $('#dxmPackageDetailDiv').html(data);
                                $('#packageDetailModal').modal('hide').modal('show');
                                var $keepState = $('#keepState'),
                                    $upbtnForOrder = $('#upbtnForOrder'),
                                    $downbtnForOrder = $('#downbtnForOrder'),
                                    orderIds = $keepState.data('orderIds'), //订单id数组
                                    currOrderNum = $keepState.data('currOrderNum'), //当前订单的id在数组中的位置
                                    currPage = $('#pageNo').val(), //当前页
                                    totalPage = $('#totalPage').val(); //总页数

                                currOrderNum = parseInt(currOrderNum);
                                currPage = parseInt(currPage);
                                totalPage = parseInt(totalPage);
                                if(orderIds) {
                                    if(orderIds.length === 1){//当前页只有一条
                                        $upbtnForOrder.attr('onclick', '');
                                        $downbtnForOrder.attr('onclick', '');
                                        $('#upOrDownDiv').css('display', 'none');
                                    }else if (currOrderNum === -1) {
                                        for (i = 0; i < orderIds.length; i++) {
                                            if (packageId == orderIds[i]) {
                                                currOrderNum = i;
                                                break;
                                            }
                                        }
                                        $keepState.data('currOrderNum', currOrderNum);
                                    }
                                    if(currPage === 1 && !currOrderNum){//第一页第一条
                                        $upbtnForOrder.attr('onclick', '').addClass('btn-disabled');
                                        $('#upShow').attr('data-original-title', '已经是第一个了');
                                    }else if(currPage === totalPage && currOrderNum === (orderIds.length - 1)){//最后一页最后一条
                                        $downbtnForOrder.attr('onclick', '').addClass('btn-disabled');
                                        $('#downShow').attr('data-original-title', '已经是最后一个了');
                                    }
                                }
                                $('[data-toggle="popover"]').popover({
                                    trigger: 'hover'
                                });
                                // 设置报关总额
                                allCustomsForm();
                                refreshOrderProfit(1, packageId.toString());
                                showLogisticInfo(authId, agentNameType, orderPlatform, apacPickUpType, showCodAmount, codType, sizeType);
                            },
                            error: function () {
                                $.fn.message({type: 'error', msg: '网络异常，请稍后重试！'});
                                $('#loading').modal('hide');
                            }
                        });
                        $('#executeChangePackageNumModel').empty();
                    }
                }else {
                    // 普通物流 (没有物流相关信息)
                    $('#loading').modal('show');
                    $.ajax({
                        type: 'POST',
                        url: 'package/updatePackageLogistic.json',
                        data: {
                            packageId: packageId,
                            authId: authId,
                            agentNameType: agentNameType
                        },
                        dataType: 'json',
                        success: function(data) {
                            $('#loading').modal('hide');
                            if (!+data.code) {
                                $.fn.message({type: 'success', msg: '操作成功!'});
                                if (!+type) {
                                    //列表页
                                    refreshAjaxPage();
                                } else if (+type === 1) {
                                    var oldAgentNameType = $('#agentNameType').val(),	// 原物流方式
                                        $parentOrderOldAuthId = $('#parentOrderOldAuthId'),
                                        oldAuthId = $parentOrderOldAuthId.val(),
                                        $agentAndLogisticFeeModal = $('#agentAndLogisticFeeModal'),
                                        $orderPackageStockSpan = $('#orderPackageStockSpan'),
                                        $orderPackageStockSelectId = $('#orderPackageStockSelectId'),
                                        $agentProviderDiv = $('#agentProviderDiv');
                                    //详情页
                                    $agentAndLogisticFeeModal.modal('hide');
                                    $('#detailPackageAuthId').val(authId);
                                    $('#detailPackageAgentProvider').val(agentProviderName);
                                    //更新物流方式链接
                                    $agentProviderDiv.find('a').attr('href', 'providerAuth/editSetIndex.htm?apAuthId=' + authId + '&fromOrder=1')
                                        .html('<span class="inline-block">' + agentProviderName + '</span>');
                                    if (agentNameType >= 10000) {
                                        $orderPackageStockSpan.html(data.overseaWarehoseName).css('display', '');
                                        $('#platform').val(data.platform);
                                        $orderPackageStockSelectId.css('display', 'none');
                                    } else {
                                        $orderPackageStockSpan.text('').css('display', 'none');
                                        if(oldAgentNameType >= 10000){
                                            $orderPackageStockSelectId.val(data.storageId);
                                        }
                                        $orderPackageStockSelectId.css('display', '');
                                    }
                                    $agentAndLogisticFeeModal.find('#logisticTemplate_' + oldAuthId)
                                        .html('使用此物流').data('value', '0').removeClass('gray-c');

                                    $agentAndLogisticFeeModal.find("#logisticTemplate_"+authId).html('已选择').data('value', '1').addClass('gray-c');
                                    $agentProviderDiv.html('<a href="providerAuth/editSetIndex.htm?apAuthId=' + authId + '&fromOrder=1"' +
                                        ' target="_blank">' + agentProviderName + '</a>');
                                    $parentOrderOldAuthId.val(authId);
                                    // 隐藏物流承运商设置
                                    $('#smtAgentDiv').css('display', 'none');
                                    $('#postPonyDiv').css('display', 'none');
                                    $('#zwsdAgentDiv').css('display', 'none');
                                    $('#heLianDiv').css('display', 'none');
                                }
                            } else {
                                $.fn.message({type: 'error', msg: data.msg});
                            }
                        },
                        error:function(){
                            $.fn.message({type: 'error', msg: '网络异常，请稍后重试！'});
                            $('#loading').modal('hide');
                        }
                    });
                }
            }
        }
    });
};
/** 运费总览 更新包裹物流方式  end**/

/** 速卖通线上发货、PostPony、中乌速递、合联物流方式 信息回显  **/
var showLogisticInfo = function (authId,agentNameType,platform,apacPickUpType, showCodAmount, codType, sizeType, agentPackageCountType) {
    $('#isEditState').val('edit');
    showHideInfo("updateLogisticsInformation","logisticsInformation");
    if(authId > 0){
        if(agentNameType == 256 || agentNameType == 419){
            var expressId = $("#expressId").val();
            $.ajax({
                type: "POST",
                url: 'smtExpress/getExpress.json',
                data: {},
                dataType: "json",
                success: function (data) {
                    var list = data.list;
                    var str = "<option value='0'>请选择</option>";
                    for (var i = 0; i < list.length; i++) {
                        if (expressId == list[i].companyId) {
                            str += "<option value='" + list[i].companyId + "' selected>" + list[i].name + "</option>";
                        } else {
                            str += "<option value='" + list[i].companyId + "'>" + list[i].name + "</option>";
                        }
                    }
                    $("#expressSelect").empty();
                    $("#expressSelect").html(str);
                    // 中乌速递乌克兰专线回显
                    $("#zwsdExpressSelected").empty();
                    $("#zwsdExpressSelected").html(str);
                    var inlandExpressId = $("#inlandExpressId").val();
                    $("#zwsdExpressSelected option").each(function () {
                        if($(this).val() == inlandExpressId){
                            $(this).prop("selected",true);
                        }
                    });
                },
                error: function () {
                    $('#loading').modal('hide');
                }
            });
        }
        if(platform == 'smt'){
            var expressId = $("#expressId").val();
            $.ajax({
                type: "POST",
                url: 'smtExpress/getExpress.json',
                data: {},
                dataType: "json",
                success: function(data){
                    var list = data.list;
                    var str = "<option value='0'>请选择</option>";
                    for(var i=0;i<list.length;i++){
                        if(expressId == list[i].companyId){
                            str += "<option value='" + list[i].companyId + "' selected>" + list[i].name + "</option>";

                        } else {
                            str += "<option value='" + list[i].companyId + "'>" + list[i].name + "</option>";
                        }
                    }
                    $("#expressSelect").empty();
                    $("#expressSelect").html(str);
                },
                error:function(){
                    $('#loading').modal('hide');
                }
            });
        }
        $("#updateShipInfoAuthSelect").val(authId);
        if(agentNameType == 105 || agentNameType == 655 || agentNameType == 448 || agentNameType == 734 || sizeType == 1){
            if(agentNameType == 655 || agentNameType == 448 || agentNameType == 734 || sizeType == 1){
                $("[name='alibabaOnlineDisplay']").css("display", "none");
                if(agentNameType == 655){
                    $(".inlandExpressCodeBox").removeClass("hide");
                }
            }
            // postPony物流
            $("#postPonyExpressDiv").css("display", "");
        } else {
            $("#postPonyExpressDiv").css("display", "none");
        }

        if (agentPackageCountType == 1) {
            $("[name='agentPackageCountDisplay']").css("display", "");
        } else {
            $("[name='agentPackageCountDisplay']").css("display", "none");
        }

        if(agentNameType == 256 || agentNameType == 419){
            // 回显
            $("#zwsdExpressTrackNumber").val($("#inlandExpressNumberHidden").val());
            $("#zwsdWklExpressDiv").css("display", "");
        } else {
            $("#zwsdWklExpressDiv").css("display", "none");
        }

        if(agentNameType == 22) {
            // 显示速卖通物流承运商设置
            $("#smtExpressDiv").css("display", "");
            var $smtExpressName = $("#smtExpressDiv").find('.smtExpressName');
            if ($smtExpressName) $smtExpressName.css('display', 'none');
            $("#postPonyExpressDiv").css("display", "none");
            $("#zwsdWklExpressDiv").css("display", "none");
            $("#heLianExpressDiv").css("display", "none");
            setSmtOnline();
        }else{
            $("#smtExpressDiv").css("display", "none");
        }
        if (agentNameType == 353 || (agentNameType == 704 && apacPickUpType == 1) || (agentNameType == 3 && showCodAmount == 1) || (codType == 1 && showCodAmount == 1)) {
            //合联物流
            $("#heLianExpressCodAmount").val($("#heLianCodAmountHidden").val());
            $("#heLianExpressDiv").css("display", "");
        } else {
            $("#heLianExpressDiv").css("display", "none");
        }
    }
};
/** 速卖通线上发货、PostPony、中乌速递、合联物流方式 信息回显 End **/


/** 波次-- 发货中禁止发货 **/
var showSignWavePackageBanShip = function (packageId,isSingle) {
    if(1 == isSingle){
        //单个禁止发货
        $('#waveSignBanshipBtn').attr('onclick', 'signWavePackageBanShip()');
    } else if (0 == isSingle){
        //批量禁止发货
        $('#waveSignBanshipBtn').attr('onclick', 'batchWaveSignBanShip()');
    }
    $('#banshipWavePackageId').val(packageId);
    $('#wavePackageBanShipNote').val('');
    $('#wavePackageBanShipReasonCode').val('4');
    $('#signWavePackageBanShipModal').modal('show');
};

var signWavePackBanShipFlag = false;
var signWavePackageBanShip = function () {
    if(signWavePackBanShipFlag){
        return;
    }
    signWavePackBanShipFlag = true;
    var packageId =  $('#banshipWavePackageId').val();
    var type = $('#wavePackageBanShipReasonCode').val();
    var wavePackageBanShipNote = $.trim($('#wavePackageBanShipNote').val());
    if(type == 5 && wavePackageBanShipNote.length == 0){
        $.fn.message({type: "error", msg: "请输入原因内容!"});
        signWavePackBanShipFlag = false;
        return;
    }
    $('#loading').modal('show');
    $.ajax({
        type: "POST",
        url: 'package/signWavePackageBanShip.json',
        data: {
            packageId: packageId,
            type: type,
            wavePackageBanShipNote: wavePackageBanShipNote
        },
        dataType: "json",
        success: function(data){
            signWavePackBanShipFlag = false;
            $('#loading').modal('hide');
            $('#signWavePackageBanShipModal').modal('hide');
            if (data.code == 0) {
                $.fn.message({type: "success", msg: "操作成功!"});
                refreshAjaxPage();
            } else {
                $.fn.message({type: "error", msg: data.msg});
            }
        },
        error:function(){
            signWavePackBanShipFlag = false;
            $('#loading').modal('hide');
        }
    });
};

/** 打回包裹展示 **/
var wavePackageMoveToApproved = function (packageId) {
    $('#wavePackageMoveToApprovedBtn').attr('onclick', 'invalidWavePackage("' + packageId+'")');
    $("#wavePackageMoveToApproved").modal("show");
};

/** 打回包裹 **/
var isInvalidWavePackage = false;
var invalidWavePackage = function (packageId) {
    if (isInvalidWavePackage) {
        return;
    }
    isInvalidWavePackage = true;
    if(packageId == undefined || packageId == null || packageId ==''){
        $.fn.message({type: "error", msg: "包裹号不能为空！"});
        isInvalidWavePackage = false;
        return;
    }
    $('#loading').modal('show');
    $.ajax({
        type: "POST",
        url: 'package/invalidPackage.json',
        data: {"packageId": packageId},
        dataType: "json",
        success: function (data) {
            $('#loading').modal('hide');
            var code = data.code;
            if (code == 0) {
                $.fn.message({type: "success", msg: "操作成功，订单已移入到「待处理」页！"});
                refreshAjaxPage();
            } else {
                $.fn.message({type: "error", msg: data.msg});
            }
            $('#wavePackageMoveToApproved').modal('hide');
            isInvalidWavePackage = false;
        },
        error: function () {
            $('#loading').modal('hide');
            isInvalidWavePackage = false;
        }
    });
};

//波次--批量禁止发货
var isBatchWaveSignBanShip = false;
var batchWaveSignBanShip = function () {
    if(isBatchWaveSignBanShip){
        return;
    }
    isBatchWaveSignBanShip = true;
    var packageIds = getCheckBoxValByName("packageId");
    if (packageIds === '') {
        $.fn.message({type: "error", msg: "请至少选择一个订单"});
        isBatchWaveSignBanShip = false;
        return;
    }
    var type = $('#wavePackageBanShipReasonCode').val();
    var wavePackageBanShipNote = $.trim($('#wavePackageBanShipNote').val());
    if(type == 5 && wavePackageBanShipNote.length == 0){
        $.fn.message({type: "error", msg: "请输入原因内容!"});
        isBatchWaveSignBanShip = false;
        return;
    }
    $('#loading').modal('show');
    $.ajax({
        type: "POST",
        url: 'package/batchWaveSignBanShip.json',
        data: {
            packageIds: packageIds,
            type: type,
            wavePackageBanShipNote: wavePackageBanShipNote
        },
        dataType: "json",
        success: function(data){
            isBatchWaveSignBanShip = false;
            $('#loading').modal('hide');
            $('#signWavePackageBanShipModal').modal('hide');
            if (data.code == 0) {
                if(data.code == 0){
                    var successList = data.bor.successList;
                    var failList = data.bor.failList;
                    batchReturnProcess(successList, failList, "订单已移入到「禁止发货」页！");
                }else {
                    $.fn.message({type: "error", msg: data.msg});
                }
            } else {
                $.fn.message({type: "error", msg: data.msg});
            }
            refreshAjaxPage();
        },
        error:function(){
            isBatchWaveSignBanShip = false;
            $('#loading').modal('hide');
        }
    });
};


/** 批量移入波次 **/
var isBatchMoveToWave = false;
var batchMoveToWave = function () {
    if (isBatchMoveToWave) {
        return;
    }
    isBatchMoveToWave = true;
    // 如果没有选中所有页，要判断用户是否已选择订单
    var packageIds = getCheckBoxValByName("packageId");
    if (packageIds == "") {
        $.fn.message({type: "error", msg: "请至少选择一个订单"});
        isBatchMoveToWave = false;
        return;
    }
    $('#loading').modal('show');
    $.ajax({
        type: "POST",
        url: 'package/batchMoveToWave.json',
        data: {"packageIds": packageIds},
        dataType: "json",
        success: function (data) {
            if(data.code == 0){
                var successList = data.bor.successList;
                var failList = data.bor.failList;
                batchReturnProcess(successList, failList, "订单已移入到「发货中」页！");
            }else {
                $.fn.message({type: "error", msg: data.msg});
            }
            refreshAjaxPage();
            isBatchMoveToWave = false;
            $('#loading').modal('hide');
        },
        error: function () {
            $('#loading').modal('hide');
            isBatchMoveToWave = false;
        }
    });
};

/** 异常订单发货 **/
var isYuncang = false;
var submitYuncang = function (packageId) {
    if (isYuncang) {
        return;
    }
    isYuncang = true;
    $('#loading').modal('show');
    $.ajax({
        type: "POST",
        url: 'package/submitYuncang.json',
        data: {
            "packageId": packageId
        },
        dataType: "json",
        success: function (data) {
            $('#loading').modal('hide');
            if (data.code == 0) {
                $.fn.message({type: "success", msg: "操作成功，订单正在提交云仓中！"});
                $("#packageDetailModal").modal("hide");
                refreshAjaxPage();
            } else {
                /*2017.5.17 byzym 添加URL包裹*/
                var msg = strFilterUrl(data.msg);
                $.fn.message({type: "error", msg: msg});
            }
            isYuncang = false;
        },
        error: function () {
            $('#loading').modal('hide');
            isYuncang = false;
        }
    });
};

/** 批量取消发货  **/
var isBatchYuncang = false;
var batchSubmitYuncang = function () {
    // 如果没有选中所有页，要判断用户是否已选择订单
    var packageIds = getCheckBoxValByName("packageId");
    if(packageIds == ""){
        $.fn.message({type:"error",msg:"请至少选择一个订单"});
        isBatchYuncang = false;
        return;
    }
    var packageArr = packageIds.split(",");
    var notPrintMdNum = 0;
    var isPrintpackage;
    var authId;
    for(var i=0;i<packageArr.length;i++){
        isPrintpackage = $('#printMd'+packageArr[i]);
        authId = $('#dxmAuthId'+packageArr[i]).val();
        if(isPrintpackage.length == 1 || authId == 0){
            continue;
        }
        notPrintMdNum += 1;
    }
    var contentTip = '确定要提交？';
    if(notPrintMdNum>0){
        contentTip = '<span style="line-height: 22px"><span class="fW600">当前选中'+(packageArr.length)+'条数据，</span></br>'+'确定要再次提交？</span>';
    }
    myjAlert.confirm({
        'content': contentTip,
        'callback':function(v){
            if(v){
                if(isBatchYuncang){
                    return;
                }
                isBatchYuncang = true;
                $('#loading').modal('show');
                $.ajax({
                    type: "POST",
                    url: 'package/batchSubmitYuncang.json',
                    data: {"packageIds":packageIds},
                    dataType: "json",
                    success: function(data){
                        if(data.code == 0){
                            var successList = data.bor.successList;
                            var failList 	= data.bor.failList;
                            batchReturnProcess(successList, failList, "订单已提交云仓，请等待审核结果！");
                            refreshAjaxPage();
                        }else{
                            /*2017.5.17 byzym 添加URL包裹*/
                            var msg = strFilterUrl(data.msg);
                            $.fn.message({type: "error", msg: msg});
                        }
                        isBatchYuncang = false;
                    },
                    error:function(){
                        $('#loading').modal('hide');
                        isBatchYuncang = false;
                    }
                });
            }
        }
    });
};

// 强制占用
var isForceLock = false;
var forceLock = function (packageId) {
    if (isForceLock) {
        return;
    }
    isForceLock = true;
    $('#loading').modal('show');
    $.ajax({
        type: "POST",
        url: 'package/forceLock.json',
        data: {
            "packageId": packageId
        },
        dataType: "json",
        success: function (data) {
            $('#loading').modal('hide');
            if (!+data.code) {
                $.fn.message({type: "success", msg: "操作成功！"});
                $("#packageDetailModal").modal("hide");
                refreshAjaxPage();
            } else {
                /*2017.5.17 byzym 添加URL包裹*/
                var msg = strFilterUrl(data.msg);
                $.fn.message({type: "error", msg: msg});
            }
            isForceLock = false;
        },
        error: function () {
            $('#loading').modal('hide');
            isForceLock = false;
        }
    });
};

// 批量强制占用
var isBatchForceLock = false;
var batchForceLock = function () {
    // 如果没有选中所有页，要判断用户是否已选择订单
    var packageIds = getCheckBoxValByName("packageId");
    if(packageIds == ""){
        $.fn.message({type:"error",msg:"请至少选择一个订单"});
        return;
    }
    var packageArr = packageIds.split(",");
    var notPrintMdNum = 0;
    var isPrintpackage;
    var authId;
    for(var i=0;i<packageArr.length;i++){
        isPrintpackage = $('#printMd'+packageArr[i]);
        authId = $('#dxmAuthId'+packageArr[i]).val();
        if(isPrintpackage.length === 1 || authId === 0){
            continue;
        }
        notPrintMdNum += 1;
    }
    var contentTip = '确定要强制占用吗？';
    if(notPrintMdNum>0){
        contentTip = '<span style="line-height: 22px"><span class="fW600">当前选中'+(packageArr.length)+'条数据，</span></br>'+'确定要强制占用？</span>';
    }
    myjAlert.confirm({
        content: contentTip,
        callback: function(v){
            if(v){
                if(isBatchForceLock){
                    return;
                }
                isBatchForceLock = true;
                $('#loading').modal('show');
                $.ajax({
                    type: "POST",
                    url: 'package/batchForceLock.json',
                    data: {"packageIds":packageIds},
                    dataType: "json",
                    success: function(data){
                        if(!+data.code){
                            var successList = data.bor.successList;
                            var failList 	= data.bor.failList;
                            batchReturnProcess(successList, failList, "订单已提交云仓，请等待审核结果！");
                            refreshAjaxPage();
                        }else{
                            /*2017.5.17 byzym 添加URL包裹*/
                            var msg = strFilterUrl(data.msg);
                            $.fn.message({type: "error", msg: msg});
                        }
                        isBatchForceLock = false;
                    },
                    error:function(){
                        $('#loading').modal('hide');
                        isBatchForceLock = false;
                    }
                });
            }
        }
    });
};
